//
//  STFNetworkTools.swift
//  swift网络封装
//
//  Created by 沈腾飞 on 2017/1/18.
//  Copyright © 2017年 shen. All rights reserved.
//

import UIKit
import AFNetworking

//请求方法枚举

enum STFNetworkToolsMethod:String {
    case get = "get"
    case post = "post"
}


class STFNetworkTools: AFHTTPSessionManager {
    
    //全局访问点
    static let shared:STFNetworkTools = {
        
        let net = STFNetworkTools()
        //增加支持的数据类型
        net.responseSerializer.acceptableContentTypes?.insert("text/html")
        net.responseSerializer.acceptableContentTypes?.insert("text/plain")
       
        
        return net
        
        
    }()
    
    func request(Method:STFNetworkToolsMethod,urlString:String,parameters:Any?,success:@escaping (Any?)->(),failure:@escaping (Error)->()) {
        
        if Method == .get {
            self.get(urlString, parameters: parameters, progress: nil, success: { (_, res) in
                //执行闭包
                success(res)
            }, failure: { (_, err) in
                //执行闭包
                failure(err)
            })
        } else {
            
            self.post(urlString, parameters: parameters, progress: nil, success: { (_, res) in
                //执行闭包
                success(res)
            }, failure: { (_, err) in
                //执行闭包
                failure(err)
            })
        }
    }
//    func loadData (success:@escaping (Any?)->(),failure:@escaping (Error)->()) {
//        
//        //请求URL
//        let urlString = "http://www.weather.com.cn/data/sk/101010100.html"
//        
//        //发送请求
//        self.request(Method:STFNetworkToolsMethod.get, urlString: urlString, parameters: nil, success: success, failure: failure)
//        
//        
//    }

}

//MARK : - OAuth网络请求
extension STFNetworkTools {
    
    // 请求获取accessToken
    func getUserAccount(code:String,success:@escaping (Any?)->(),failure:@escaping (Error)->()) {
        
        //请求的URL
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求的参数
        let params = [
            "client_id" : APPKEY,
            "client_secret" : APPSECRET,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : REDIRECT_URI
        ]
        //发送请求
        request(Method: STFNetworkToolsMethod.post, urlString: urlString, parameters: params, success: success, failure: failure)
        
        
    }
        //MARK : - 获取用户信息请求
    // 获取用户信息数据
    func loadUserInfo(userAccountModel: STFUserAccountModel, success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        // 请求的url
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求的参数
        let params = [
            "access_token":userAccountModel.access_token!,
            "uid": userAccountModel.uid!
        ]
        // 发送请求
        request(Method: STFNetworkToolsMethod.get, urlString: urlString, parameters: params, success: success, failure: failure)
    }

  
}


